package com.paireach.bw.fragment;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.blankj.utilcode.utils.ConstUtils;
import com.blankj.utilcode.utils.NetworkUtils;
import com.blankj.utilcode.utils.TimeUtils;
import com.paireach.bw.R;
import com.paireach.bw.activity.BackActivity;
import com.paireach.bw.activity.CommonActivity;
import com.paireach.bw.activity.KaActivity;
import com.paireach.bw.activity.SafeCheckActivity;
import com.paireach.bw.activity.ServiceEvaluationActivity;
import com.paireach.bw.activity.StartTransActivity;
import com.paireach.bw.adapter.FragHomeAdapter;
import com.paireach.bw.application.MyApplication;
import com.paireach.bw.base.BaseFragment;
import com.paireach.bw.bean.DriveOrder;
import com.paireach.bw.bean.HomeBean;
import com.paireach.bw.bean.LocationInfo;
import com.paireach.bw.bean.ReturnInfo;
import com.paireach.bw.broadcastreceiver.NetStatueUtil;
import com.paireach.bw.event.AppEvent;
import com.paireach.bw.event.HttpErrorEvent;
import com.paireach.bw.event.HttpSuccessEvent;
import com.paireach.bw.http.RequestTag;
import com.paireach.bw.http.WayBillRequest;
import com.paireach.bw.utils.BDTraceUtil;
import com.paireach.bw.utils.GsonUtil;
import com.paireach.bw.utils.LocationService;
import com.paireach.bw.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;

/**
 * Created by ${cqc} on 2017/2/3.
 */

public class HomeFrag extends BaseFragment implements View.OnClickListener, FragHomeAdapter.OnItemClickListener {

    private static final String TAG = "HomeFrag";
    private Context context;
    private View rootView;
    private String name, phone;
    private TextView main_userphone, main_username, tv_title;
    private LinearLayout layout_phone;
    private AlertDialog dialog;
    private Button btn_check;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private List<DriveOrder> orderList = new ArrayList<>();
    private FragHomeAdapter adapter;
    private Intent intent212;
    private Intent intent220;
    private Intent intent226;
    private Intent intent228;
    private Intent intent230;
    private TextView tv_check;


    private boolean isViewCreated = false;
    private LocationService locationService;

    public static HomeFrag getInstance(String name, String phone) {
        HomeFrag homeFragment = new HomeFrag();
        Bundle bundle = new Bundle();
        bundle.putString("white_border_bg", name);
        bundle.putString("phone", phone);
        homeFragment.setArguments(bundle);
        return homeFragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isViewCreated) {
            refreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(true);
                    onRefreshListener.onRefresh();
                }
            });
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            name = bundle.getString("white_border_bg");
            phone = bundle.getString("phone");
        }
        context = getActivity();
        new WayBillRequest().isSafeCheckCommit(phone);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = LayoutInflater.from(container.getContext()).inflate(R.layout.frag_home, container, false);
        findViews();
        initViews();
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
    }

    @Override
    public void onStart() {
        super.onStart();
        // -----------location config ------------
        locationService = ((MyApplication) getActivity().getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshLayout.setRefreshing(true);
        onRefreshListener.onRefresh();
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LocationInfo locationInfo = ((MyApplication) getActivity().getApplication()).locationInfo;
                locationInfo.setTime(location.getTime());
                locationInfo.setLongitude(location.getLongitude());
                locationInfo.setLatitude(location.getLatitude());
                locationInfo.setAddStr(location.getAddrStr());
                LogUtil.d(locationInfo.getAddStr());
            }
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };


    private void initViews() {
        main_username.setText(name);
        main_userphone.setText(phone);
        btn_check.setOnClickListener(this);
        layout_phone.setOnClickListener(this);

        refreshLayout.setColorSchemeResources(R.color.item3, R.color.item11, R.color.gold);
        refreshLayout.setOnRefreshListener(onRefreshListener);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        adapter = new FragHomeAdapter(orderList);
        recyclerView.setAdapter(adapter);

        adapter.setmOnItemClickListener(this);
    }

    private SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
//            if (NetworkUtils.isConnected()) {
                new WayBillRequest().loadHomeOrder(phone);
//            } else {
//                showToast("网络连接不可用，请稍后重试");
//            }
        }
    };

    private void findViews() {
        main_userphone = (TextView) rootView.findViewById(R.id.main_userphone);
        main_username = (TextView) rootView.findViewById(R.id.main_username);
        btn_check = (Button) rootView.findViewById(R.id.btn_check);
        tv_check = (TextView) rootView.findViewById(R.id.tv_check);
        layout_phone = (LinearLayout) rootView.findViewById(R.id.layout_phone);

        tv_title = (TextView) rootView.findViewById(R.id.tv_title);
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refreshLayout);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_phone:
                showPhoneDialog();
                break;
            case R.id.btn_check:
                Intent intent = new Intent(getActivity(), SafeCheckActivity.class);
                ActivityOptionsCompat option1 = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity());
                ActivityCompat.startActivity(getActivity(), intent, option1.toBundle());
                break;
        }
    }


    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.LOAD_HOME_ORDER || event.getRequestTag() == RequestTag.IS_SAFE_CHECK_COMMIT) {
            dismissProgressDialog();
            refreshLayout.setRefreshing(false);
            orderList.clear();
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        if (event.getRequestTag() == RequestTag.LOAD_HOME_ORDER) {
            refreshLayout.setRefreshing(false);
            if (TextUtils.isEmpty(event.getJson())) {
                showToast("系统错误");
                orderList.clear();
                adapter.notifyDataSetChanged();
            } else {
                orderList.clear();
                HomeBean bean = GsonUtil.jsonToBean(event.getJson(), HomeBean.class);
                if (bean == null) {
                    showToast("数据错误");
                } else {
                    if (1 == bean.getStatus()) {
                        String type = bean.getType();
                        switch (type) {
                            case "unabsorbed":
                                tv_title.setText("新单提示");
                                break;
                            case "distribution":
                                tv_title.setText("配送中");
                                if (bean.getData().size() == 0 || bean.getData() == null) {
                                    new NetStatueUtil().destroyReceiver(context);
                                    BDTraceUtil.closeTrace();
                                    locationService.unregisterListener(mListener); //注销掉监听
                                    locationService.stop(); //停止定位服务
                                } else {
                                    //开启百度鹰眼
                                    locationService.start();
                                    BDTraceUtil.openTrace();
                                    //超过3天的通知
                                    show3DaysNotification(bean.getData());
                                }
                                break;
                        }
                        orderList.addAll(bean.getData());
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter.notifyDataSetChanged();
                        tv_title.setText("暂无运单");
                        BDTraceUtil.closeTrace();
                        locationService.unregisterListener(mListener); //注销掉监听
                        locationService.stop(); //停止
                    }
                }
            }
        } else if (event.getRequestTag() == RequestTag.IS_SAFE_CHECK_COMMIT) {
            jsonParse(event.getJson());
        }
    }

    private void show3DaysNotification(List<DriveOrder> data) {
        StringBuffer sb = new StringBuffer();
        if (data.size() > 0) {
            try {
                for (int i = 0; i < data.size(); i++) {
                    String accept_time = data.get(i).getDRIVER_ORDER_TIME();
                    long days = TimeUtils.getTimeSpanByNow(accept_time, ConstUtils.TimeUnit.DAY);
                    if (days > 3) {
                        sb.append(data.get(i).getCODE() + ",");
                    }
                }
                if (!TextUtils.isEmpty(sb.toString())) {
                    showNotification(sb.toString());
                }
            } catch (Exception e) {

            }
        }
    }

    private static void showNotification(String contentText) {
        NotificationManager manager = (NotificationManager) MyApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(MyApplication.getContext());
        builder.setContentTitle("百威-我来运")
                .setContentText("单号：" + contentText + "已超过3天，还未签收!")
                .setLargeIcon(BitmapFactory.decodeResource(MyApplication.getContext().getResources(), R.mipmap.tts_logo_1))
                .setSmallIcon(R.mipmap.logo16)//6.0是个白色 圆圈,而且必须加
                .setDefaults(Notification.DEFAULT_ALL)
                .setAutoCancel(true);

        Notification notification = builder.build();
//            notification.flags = Notification.FLAG_INSISTENT;//不点击的话会一直震动
        manager.notify(2, notification);
    }

    private void jsonParse(String json) {
        ReturnInfo info = GsonUtil.jsonToBean(json, ReturnInfo.class);
        if (info.getStatus() == 1) {
            tv_check.setVisibility(View.GONE);
        } else {
            showToast(info.getMsg());
            tv_check.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
        if ("已经安全检查过了".equals(event.getExtraInfo())) {
            tv_check.setVisibility(View.GONE);
        }
    }

    //拨打电话的dialog
    private void showPhoneDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("服务电话");
        builder.setMessage("是否拨打电话:" + getResources().getString(R.string.service_phone));
        builder.setCancelable(true);
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + getResources().getString(R.string.service_phone)));
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }


    @Override
    public void onItemClick(View view, int position) {
        if (NetworkUtils.isConnected()) {
            DriveOrder driverOrder = orderList.get(position);
            String status = driverOrder.getSTATUS();
            String transport_code = driverOrder.getTRANSPORT_CODE();

            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity());
            switch (status) {
                case "212":
                    if ("BACK".equals(transport_code)) {
                        intent212 = new Intent(context, BackActivity.class);
                    } else if ("COMMON".equals(transport_code)) {
                        intent212 = new Intent(context, CommonActivity.class);
                    } else {
                        intent212 = new Intent(context, KaActivity.class);
                    }
                    intent212.putExtra("orderCode", driverOrder.getCODE());
                    ActivityCompat.startActivity(context, intent212, options.toBundle());
                    break;
                case "220":
                    if ("BACK".equals(transport_code)) {
                        intent220 = new Intent(context, BackActivity.class);
                    } else if ("COMMON".equals(transport_code)) {
                        intent220 = new Intent(context, CommonActivity.class);
                    } else {
                        intent220 = new Intent(context, KaActivity.class);
                    }
                    intent220.putExtra("orderCode", driverOrder.getCODE());
                    ActivityCompat.startActivity(getActivity(), intent220, options.toBundle());
                    break;
                case "226":
                    if ("BACK".equals(transport_code)) {
                        intent226 = new Intent(context, BackActivity.class);
                    } else if ("COMMON".equals(transport_code)) {
                        intent226 = new Intent(context, CommonActivity.class);
                    } else {
                        intent226 = new Intent(context, KaActivity.class);
                    }
                    intent226.putExtra("orderCode", driverOrder.getCODE());
                    startActivity(intent226);
                    break;
                case "228"://发货地： 出厂
                    if ("BACK".equals(transport_code)) {
                        intent228 = new Intent(context, BackActivity.class);
                    } else if ("COMMON".equals(transport_code)) {
                        intent228 = new Intent(context, CommonActivity.class);
                    } else {
                        intent228 = new Intent(context, KaActivity.class);
                    }
                    intent228.putExtra("orderCode", driverOrder.getCODE());
                    startActivity(intent228);
                    break;
                case "230":
                    if ("BACK".equals(transport_code)) {//回瓶
                        intent230 = new Intent(context, BackActivity.class);
                    } else if ("KA".equals(transport_code)) {//KA的负载单状态也不变了，直到交货单全部走完，直接走245
                        intent230 = new Intent(context, KaActivity.class);
                    } else {//常规的负载单状态不变了，直到交货单全部走完，直接走245
                        intent230 = new Intent(context, CommonActivity.class);
                    }
                    intent230.putExtra("orderCode", driverOrder.getCODE());
                    startActivity(intent230);
                    break;
                case "245":
                    ActivityOptionsCompat options245 = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity());
                    Intent intent245 = new Intent(context, ServiceEvaluationActivity.class);
                    intent245.putExtra("orderCode", driverOrder.getCODE());
                    ActivityCompat.startActivity(getActivity(), intent245, options245.toBundle());
                    break;
//            default:
//                Toasty.info(context, "负载单状态：" + driverOrder.getSTATUS() + " 状态名称：" + driverOrder.getSTATUS_NAME()).show();
//                break;
            }
        } else {
            showToast("网络连接不可用，请稍后重试");
        }
    }
}
